package com.chencs.durid.datasoure;

import com.alibaba.druid.pool.DruidDataSource;
import com.chencs.durid.config.DatasourceProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by chencs on 2017/5/26.
 */
@Configuration
@EnableConfigurationProperties(value={DatasourceProperties.class})
public class DataSourceConfiguration {

    private Logger logger = LoggerFactory.getLogger(DataSourceConfiguration.class);

    @Autowired
    DatasourceProperties datasourceProperties;

    @Bean
    public DataSource datasource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(datasourceProperties.getUrl());
        datasource.setUsername(datasourceProperties.getUsername());
        datasource.setDriverClassName(datasourceProperties.getDriverClassName());

        datasource.setPassword(datasourceProperties.getPassword());
        //configuration
        datasource.setInitialSize(datasourceProperties.getInitialSize());
        datasource.setMinIdle(datasourceProperties.getMinIdle());
        datasource.setMaxActive(datasourceProperties.getMaxActive());
        datasource.setMaxWait(datasourceProperties.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(datasourceProperties.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(datasourceProperties.getMinEvictableIdleTimeMillis());
        datasource.setValidationQuery(datasourceProperties.getValidationQuery());
        datasource.setTestWhileIdle(datasourceProperties.isTestWhileIdle());
        datasource.setTestOnBorrow(datasourceProperties.isTestOnBorrow());
        datasource.setTestOnReturn(datasourceProperties.isTestOnReturn());
        datasource.setPoolPreparedStatements(datasourceProperties.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(datasourceProperties.getMaxPoolPreparedStatementPerConnectionSize());
        datasource.setConnectionProperties(datasourceProperties.getConnectionProperties());
        try {
            datasource.setFilters(datasourceProperties.getFilters());
            datasource.init();
            logger.info("datasource url:[{}] username:[{}] inited successfully!",datasourceProperties.getUrl(), datasourceProperties.getUsername());
        } catch (Exception e) {
            logger.error("datasource inited failed", e);
        }
        return datasource;
    }
}
